/*
 * @Author: 徐建辰
 * @Date: 2022-5-20 14:37:08
 * @LastEditTime: 2022-06-20 11:29:38
 * @LastEditors: 徐建辰
 * @Description: 处理时间格式
 */

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

/**
 * @description: 格式化js标准时间格式
 * @param {*String} date new Date()返回的中国标准时间
 * @param {*String} isHms 是否显示时分秒，默认true
 * @param {*String}
 */
export const formatDateTime = (date, isHms = true) => {
  let y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? '0' + m : m
  let d = date.getDate()
  d = d < 10 ? '0' + d : d
  let h = date.getHours()
  h = h < 10 ? '0' + h : h
  let minute = date.getMinutes()
  minute = minute < 10 ? '0' + minute : minute
  let second = date.getSeconds()
  second = second < 10 ? '0' + second : second

  const baseFormat = y + '-' + m + '-' + d
  return isHms ? baseFormat + ' ' + h + ':' + minute + ':' + second : baseFormat
}

// 格式化时间，获取周几
export const formatDateWeek = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  const now = new Date()
  const weekDay = now.getDay()
  const weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
  const curWeek = weeks[weekDay]
  const curDate = `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`

  return {curDate, curWeek}
}

/**
 * @description: 解析excel导入的时间格式
 * @param {*Number} num 当前时间戳
 * @return {*string} 
 */
 export const formatDate = num => {
  const time = new Date((num - 1) * 24 * 3600000 + 1)
  time.setYear(time.getFullYear() - 70)
  const year = time.getFullYear() + ''
  const month = time.getMonth() + 1 + ''
  const date = time.getDate() - 1 + ''

  return (year + '-' + (month < 10 ? '0': month) + '-' + (date < 10 ? '0' + date : date))
}

// 获取年
export const getYear = () => {
  let v = []
  let y = new Date().getFullYear()
  for (let i = 0; i < 11; i++) {
    v.push(y + i)
  }
  return v
}

// 日期格式化
export const dateFormat = (date, fmt='yyyy-MM-dd hh:mm:ss') => {
  date = new Date(date)
  const o = {
		'M+' : date.getMonth() + 1,                    //月份
		'd+' : date.getDate(),                         //日
		'h+' : date.getHours(),                        //小时
		'm+' : date.getMinutes(),                      //分
		's+' : date.getSeconds(),                      //秒
		'q+' : Math.floor((date.getMonth() + 3) / 3),  //季度
		'S'  : date.getMilliseconds()                  //毫秒
	}
  if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
	}
  for (let k in o) {
		if (new RegExp('('+ k +')').test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00'+ o[k]).substr(('' + o[k]).length)))
		}
	}
	return fmt
}

// 获取当前时间戳
export function getUnix() {
  return new Date().getTime()
}

// 获取今天0点0分0秒的时间戳
export function getTodayUnix() {
  const date = new Date()
  date.setHours(0)
  date.setMinutes(0)
  date.setSeconds(0)
  date.setMilliseconds(0)
  return date.getTime()
}

// 获取今年1月1日0点0秒的时间戳
export function getYearUnix() {
  const date = new Date()
  date.setMonth(0)
  date.setDate(1)
  date.setHours(0)
  date.setMinutes(0)
  date.setSeconds(0)
  date.setMilliseconds(0)
  return date.getTime()
}

// 获取标准年月日
export function getLastDate(time) {
  const date = new Date(time)
  const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  return date.getFullYear() + '-' + month + '-' + day
}

// 转换时间
export function getFormateTime(timestamp) {
  timestamp = new Date(timestamp)
  const now = getUnix()
  const today = getTodayUnix()
  const timer = (now - timestamp) / 1000
  let tip = ''

  if (timer <= 0) {
    tip = '刚刚'
  } else if (Math.floor(timer / 60) <= 0) {
    tip = '刚刚'
  } else if (timer < 3600) {
    tip = Math.floor(timer / 60) + '分钟前'
  } else if (timer >= 3600 && (timestamp - today >= 0)) {
    tip = Math.floor(timer / 3600) + '小时前'
  } else if (timer / 86400 <= 31) {
    tip = Math.ceil(timer / 86400) + '天前'
  } else {
    tip = this.getLastDate(timestamp)
  }
  return tip
}

export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}
